<template>
  <div>
    <el-card class="box-card" shadow="always">
      <div class="clearfix" slot="header">
        <b style="font-size: 18px">
          <svg-icon class="mr-10" icon-class="菜单" />菜单分配
        </b>
      </div>
      <el-row>
        <el-col :span="12">
          <el-tag type="primary" v-if="role&&role.name">{{role.name}}</el-tag>
          <el-tag type="info" v-else>
            <i class="el-icon-info"></i> 请选择角色
          </el-tag>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button @click="handleSubmit" icon="el-icon-check" type="primary">提交</el-button>
        </el-col>
      </el-row>

      <el-row style="margin-top: 10px">
        <!-- 是否联动 -->
        <!-- :check-strictly="true" -->
        <el-tree
          :data="menuOptions"
          :default-expanded-keys="expandedKeys"
          :highlight-current="true"
          :props="{label:'name'}"
          @node-click="nodeClick"
          empty-text="加载中，请稍后"
          node-key="id"
          ref="menu"
          show-checkbox
        />
      </el-row>
    </el-card>
  </div>
</template>

<script>
import MenuApi from '../../menu/api'

export default {
  name: 'Menu',
  data() {
    return {
      menuOptions: [],
      expandedKeys: [],
      role: undefined,
      initialCheckedMenuIds: []
    }
  },
  created() {
    this.loadMenus()
  },
  methods: {
    loadMenus() {
      MenuApi.getMenuList({ queryMode: '1' }).then(data => {
        this.menuOptions = data.records
        this.expandedKeys = this.menuOptions.map(node => node.id) // 展开所有节点
      })
    },
    nodeClick(data) {
      this.$emit('menuClick', data)
    },
    handleSubmit() {
      const menuIds = this.$refs.menu.getCheckedKeys().sort()
      // 判断选中菜单ID是否变动
      if (this.initialCheckedMenuIds.length === menuIds.length &&
        this.initialCheckedMenuIds.sort().every(function (v, i) {
          return v === menuIds[i]
        })) {
        this.$message.warning('数据未变动，无需提交保存')
        return
      }
      this.$api.updateRoleMenuIds({ id: this.role.id, menuIds }).then(() => {
        this.$message.success('提交成功')
      })
    },
    roleClick(role) {
      this.role = role
      this.$api.roleMenuIds({ id: role.id }).then(response => {
        this.initialCheckedMenuIds = response.data
        this.$refs.menu.setCheckedKeys(this.initialCheckedMenuIds)
      })
    }
  }
}
</script>

<style scoped>
</style>
